package me.aurora.util;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.io.UnsupportedEncodingException;

/**
 * 根据IP地址获取详细的地域信息
 * 淘宝API : http://ip.taobao.com/service/getIpInfo.php?ip=218.192.3.42
 * 新浪API : http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=218.192.3.42
 * @version 1.0
 */
public class AddressUtil {

    /**
     *
     * @param ip
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getAddresses(String ip) {
        // 这里调用淘宝API
        String url = "http://ip.taobao.com/service/getIpInfo.php?ip="+ip;
        String json = null;
        try {
            json = getResult(url);
        } catch (Exception e) {
            return "接口返回数据异常";
        }
        //处理json数据并且返回
        return parseObj(json);
    }

    /**
     * 获取json数据
     * @param url
     * @return
     */
    private static String getResult(String url) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url,String.class);
        HttpStatus status = responseEntity.getStatusCode();//获取返回状态
        /**
         * 如果请求通过，则返回Json数据,否则抛出异常
         */
        if(status.is2xxSuccessful()){
            return responseEntity.getBody();
        } else {
            throw new Exception();
        }
    }

    public static String parseObj(String jsonStr){
        JSONObject json = JSONUtil.parseObj(jsonStr);
        String region = JSONUtil.parseObj(json.get("data")).get("region").toString();
        String city = JSONUtil.parseObj(json.get("data")).get("city").toString();
        String address = "";
        address += region.equals("XX")?"":region;
        address += city.equals("XX")?"":city;
        return address;
    }
}
